#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <sys/ioctl.h>

#define CMD_READ_SCALE _IOR('A',1,int)

struct suctionPump_dev {
    int fd;
    int pwm_tar_duty;
};


struct flushingPump_dev {
    int fd;
    int pwm_tar_duty;
};

struct intraCavPressure_adc_dev {
    int fd;
    int scale;
    float voltage;
};

struct allPump_dev {
    struct suctionPump_dev suctionPump;
    struct flushingPump_dev flushingPump;
    struct intraCavPressure_adc_dev intraCavPressure_adc;
};


struct allPump_dev allPump;


static int allPump_init()
{
    allPump.suctionPump.fd = open("/dev/suctionPump", O_WRONLY);
	if(allPump.suctionPump.fd < 0){
		printf("file suctionPump open failed!\r\n");
		return -1;
	}
    allPump.flushingPump.fd = open("/dev/flushingPump", O_WRONLY);
	if(allPump.flushingPump.fd < 0){
		printf("file flushingPump open failed!\r\n");
		return -1;
	}
    allPump.intraCavPressure_adc.fd = open("/dev/intraCavPressure_adc", O_RDWR);
	if(allPump.intraCavPressure_adc.fd < 0){
		printf("file intraCavPressure_adc open failed!\r\n");
		return -1;
	}

}

void allPump_intraCavPressure_get_adc(void)
{
    /*读取ADC*/
	ioctl(allPump.intraCavPressure_adc.fd,CMD_READ_SCALE,&(allPump.intraCavPressure_adc.scale));
    allPump.intraCavPressure_adc.voltage = (float)((float)allPump.intraCavPressure_adc.scale * (1.8f/1024u));
	printf("ADC Voltage is %f,scale:%d\n",allPump.intraCavPressure_adc.voltage,allPump.intraCavPressure_adc.scale);
}


void allPump_suctionPump_set_pwm(int value)
{
    write(allPump.suctionPump.fd, &value, sizeof(value));
}

void allPump_flushingPump_set_pwm(int value)
{
    write(allPump.flushingPump.fd, &value, sizeof(value));
}


/*
 * @description		: main主程序
 * @param - argc 	: argv数组元素个数
 * @param - argv 	: 具体参数
 * @return 			: 0 成功;其他 失败
 */
int main(int argc, char *argv[])
{

    int tar_value;
    int test_value;

    if(argc<2)
    {
        printf("[ERROR] need input the target value\n");
        return -1;
    }
    tar_value = atoi(argv[1]);//获取目标值

    printf("target value:%d\n",tar_value);

    allPump_init();

    while(1)
    {
        
        allPump_intraCavPressure_get_adc();
        allPump_suctionPump_set_pwm(test_value);//占空比：单位为ns，最大值为1000000,最大值是由周期决定的
        allPump_flushingPump_set_pwm(test_value);//占空比：单位为ns，最大值为1000000，最大值是由周期决定的
        sleep(1);

        test_value = test_value+10;
        if(test_value>=1000000)test_value = 0;
    }
	return 0;
}